package com.klikmee.sms.chat.web.usecases;

import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;

import com.dotexe.webframework.core.ClientApplication;
import com.dotexe.webframework.core.clientactions.MessageBox;
import com.dotexe.webframework.core.datasources.CollectionDataSource;
import com.dotexe.webframework.core.triggers.Trigger;
import com.klikmee.sms.chat.web.dao.GroupDAO;
import com.klikmee.sms.chat.web.dao.QuestionDAO;
import com.klikmee.sms.chat.web.dao.QuestionResponsabilityDAO;
import com.klikmee.sms.chat.web.dao.UserSession;
import com.klikmee.sms.chat.web.util.SpringBeansLookup;
import com.klikmee.sms.services.chat.model.Agent;
import com.klikmee.sms.services.chat.model.Answer;
import com.klikmee.sms.services.chat.model.Question;
import com.klikmee.sms.services.chat.model.QuestionResponsibility;

public class MainForm extends ClientApplication {

	// private fields

	private CollectionDataSource dsAllMessages;
	private CollectionDataSource dsMyMessages;
	private CollectionDataSource dsAnsweredMessages;
	private ArrayList<String> bcAllMessages;
	private ArrayList<String> bcMyMessages;
	private ArrayList<String> bcAnsweredMessages;
	private ArrayList<Object> agentGroups;

	private List<Question> listAll = null;
	private List<com.klikmee.sms.chat.web.dto.Question> listMy = null;
	private List<com.klikmee.sms.chat.web.dto.Question> listAnswered = null;

	private QuestionDAO questionDAO = SpringBeansLookup.getBean(QuestionDAO.class);
	private GroupDAO groupDAO = SpringBeansLookup.getBean(GroupDAO.class);

	AnswerPreviewForm preview;

	// override
	@Override
	public void load() throws Exception {
		super.load();

		this.dsAllMessages = new CollectionDataSource("dsAllMessages");
		this.dsAllMessages.setMultiselect(true);
		this.getDataSources().add(this.dsAllMessages);
		this.dsMyMessages = new CollectionDataSource("dsMyMessages");
		this.getDataSources().add(this.dsMyMessages);
		this.dsAnsweredMessages = new CollectionDataSource("dsAnsweredMessages");
		this.getDataSources().add(this.dsAnsweredMessages);

		this.triggers.add(new Trigger(this, "gvMyMessageDblClick"));
		this.triggers.add(new Trigger(this, "gvAllMessageClick"));
		this.triggers.add(new Trigger(this, "btnRefreshClick"));
		this.triggers.add(new Trigger(this, "btnLogoutClick"));
		this.triggers.add(new Trigger(this, "btnAgentsSettingsClick"));
		this.triggers.add(new Trigger(this, "btnGroupSettingsClick"));
		this.triggers.add(new Trigger(this, "cmAllUnansweredMessagesAnswerClick"));
		this.triggers.add(new Trigger(this, "cmMyMessagesPreviewClick"));
		this.triggers.add(new Trigger(this, "cmAllAnsweredMessagesPreviewClick"));
		this.triggers.add(new Trigger(this, "btnBulkSendIndividualClick"));
		this.triggers.add(new Trigger(this, "btnBulkSendGroupClick"));
		this.triggers.add(new Trigger(this, "btnBulkGroupsClick"));
		this.triggers.add(new Trigger(this, "btnBulkTemplatesClick"));
		this.triggers.add(new Trigger(this, "btnBulkSignaturesClick"));

		this.bcAllMessages = new ArrayList<String>();
		this.bcAllMessages.add("FromNumber");
		this.bcAllMessages.add("Question");
		this.bcAllMessages.add("DateReceived");
		this.bcMyMessages = new ArrayList<String>();
		this.bcMyMessages.add("FromNumber");
		this.bcMyMessages.add("Question");
		this.bcMyMessages.add("DateReceived");
		this.bcMyMessages.add("Answer");
		this.bcMyMessages.add("AnswerDelivered");
		this.bcAnsweredMessages = new ArrayList<String>();
		this.bcAnsweredMessages.add("FromNumber");
		this.bcAnsweredMessages.add("Question");
		this.bcAnsweredMessages.add("DateReceived");
		this.bcAnsweredMessages.add("Answer");
		this.bcAnsweredMessages.add("AnswerDelivered");
	}

	@Override
	public void start() throws Exception {
		super.start();

		ChangeControlText("btnUser", String.format("%s %s", UserSession.getCurrentAgent().getAgentFirstName(), UserSession.getCurrentAgent().getAgentLastName()));

		agentGroups = (ArrayList<Object>) groupDAO.selectAdministrationGroupsForAgent(UserSession.getCurrentAgent());
		ChangeControlVisibility("btnAdministration", false);
		if (!agentGroups.isEmpty()) {
			ChangeControlVisibility("btnAdministration", true);
		}

		listAll = questionDAO.findUnassigned();
		this.dsAllMessages.setSource(listAll);
		this.dsAllMessages.bind(this.bcAllMessages);

		listMy = questionDAO.findByAgent(UserSession.getCurrentAgent());
		this.dsMyMessages.setSource(listMy);
		this.dsMyMessages.bind(this.bcMyMessages);

		listAnswered = questionDAO.findAnswered();
		this.dsAnsweredMessages.setSource(listAnswered);
		this.dsAnsweredMessages.bind(this.bcAnsweredMessages);
	}

	// trigger handlers
	public void btnRefreshClick() throws SecurityException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException, JSONException, NoSuchMethodException, InvocationTargetException, SQLException {
		listAll = questionDAO.findUnassigned();
		this.dsAllMessages.setSource(listAll);
		this.dsAllMessages.bind(this.bcAllMessages);
		
		listMy = questionDAO.findByAgent(UserSession.getCurrentAgent());
		this.dsMyMessages.setSource(listMy);
		this.dsMyMessages.bind(this.bcMyMessages);

		listAnswered = questionDAO.findAnswered();
		this.dsAnsweredMessages.setSource(listAnswered);
		this.dsAnsweredMessages.bind(this.bcAnsweredMessages);
	}

	public void cmAllUnansweredMessagesAnswerClick() throws SecurityException, ClassNotFoundException, Exception, IllegalAccessException, JSONException, NoSuchMethodException, InvocationTargetException {
		if (this.dsAllMessages.getSelectedItem() != null) {

			Object selectedQuestion = this.dsAllMessages.getSelectedItem();
			QuestionResponsabilityDAO questionResponsabilityDAO = SpringBeansLookup.getBean(QuestionResponsabilityDAO.class);
			Question q = (Question) selectedQuestion;
			QuestionResponsibility qr = new QuestionResponsibility();
			qr.setActive(true);
			qr.setAgent(UserSession.getCurrentAgent());
			qr.setQuestion(q);
			questionResponsabilityDAO.create(qr);

			AnswerForm answer = this.createChildApplication(AnswerForm.class);
			answer.triggers.get("btnAnswerClick").addOnFire(this, "afterAnsweredQuestion");
			answer.triggers.get("AnswerFormFormClosed").addOnFire(this, "afterAnsweredQuestion");
			this.showChildApp(answer);
			answer.setQuestionSource((Question) selectedQuestion);
			answer.setAnswerSource(new Answer());
			answer.setFromNumber(((Question) this.dsAllMessages.getSelectedItem()).getFromNumber());
			answer.start();

			listAll = questionDAO.findUnassigned();
			this.dsAllMessages.setSource(listAll);
			this.dsAllMessages.bind(this.bcAllMessages);

		} else {
			MessageBox.Show(this, "Obavestenje", "Morate selektovati pitanje!");
			return;
		}
	}

	public void cmMyMessagesPreviewClick() throws InstantiationException, IllegalAccessException, JSONException, Exception {
		preview = this.createChildApplication(AnswerPreviewForm.class);
		this.showChildApp(preview);
		preview.setPreviewSource((com.klikmee.sms.chat.web.dto.Question) this.dsMyMessages.getSelectedItem());
		preview.start();
	}

	public void cmAllAnsweredMessagesPreviewClick() throws InstantiationException, IllegalAccessException, JSONException, Exception {
		preview = this.createChildApplication(AnswerPreviewForm.class);
		this.showChildApp(preview);
		preview.setPreviewSource((com.klikmee.sms.chat.web.dto.Question) this.dsAnsweredMessages.getSelectedItem());
		preview.start();
	}

	public void afterAnsweredQuestion() throws SecurityException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException, JSONException, NoSuchMethodException, InvocationTargetException, SQLException {
		listAll = questionDAO.findUnassigned();
		this.dsAllMessages.setSource(listAll);
		this.dsAllMessages.bind(this.bcAllMessages);

		listMy = questionDAO.findByAgent(UserSession.getCurrentAgent());
		this.dsMyMessages.setSource(listMy);
		this.dsMyMessages.bind(this.bcMyMessages);

		listAnswered = questionDAO.findAnswered();
		this.dsAnsweredMessages.setSource(listAnswered);
		this.dsAnsweredMessages.bind(this.bcAnsweredMessages);
	}

	public void btnBulkSendIndividualClick() throws Exception {
		BulkSendForm bulkSend = this.createChildApplication(BulkSendForm.class);
		bulkSend.setGroupSelection(false);
		this.showChildApp(bulkSend);
		bulkSend.start();
	}
	
	public void btnBulkSendGroupClick() throws Exception {
		BulkSendForm bulkSend = this.createChildApplication(BulkSendForm.class);
		bulkSend.setGroupSelection(true);
		this.showChildApp(bulkSend);
		bulkSend.start();
	}

	public void btnBulkGroupsClick() throws Exception {
		BulkGroupForm bulkGroup = this.createChildApplication(BulkGroupForm.class);
		this.showChildApp(bulkGroup);
		bulkGroup.start();
	}

	public void btnBulkTemplatesClick() throws Exception {
		TemplateListForm templates = this.createChildApplication(TemplateListForm.class);
		this.showChildApp(templates);
		templates.start();
	}

	public void btnBulkSignaturesClick() throws Exception {
		SignatureListForm signatures = this.createChildApplication(SignatureListForm.class);
		this.showChildApp(signatures);
		signatures.start();
	}

	public void btnAgentsSettingsClick() throws InstantiationException, IllegalAccessException, JSONException, Exception {
		EmployeeListForm list = createChildApplication(EmployeeListForm.class);
		list.set_selectionMode(false);
		this.showChildApp(list);
		list.start();
	}

	public void btnGroupSettingsClick() throws InstantiationException, IllegalAccessException, JSONException, Exception {
		GroupListForm groups = createChildApplication(GroupListForm.class);
		groups.setGroupAgents(new ArrayList<Agent>());
		this.showChildApp(groups);
		groups.start();
	}

	public void btnLogoutClick() throws InstantiationException, IllegalAccessException, JSONException, Exception {
		// invalidate session
		UserSession.setCurrentAgent(null);
		// show login form
		LoginForm login = createChildApplication(LoginForm.class);
		this.showChildApp(login);
		login.start();
		this.hide();
	}
}